const Koa = require('koa')
const app = new Koa()
const path = require('path')
// 路由
const router = require('koa-router')()

// 模板引擎
const views = require('koa-views')
app.use(
  views('views', {
    map: { html: 'ejs' },
  })
)

// 获取数据
const bodyParser = require('koa-bodyparser')
app.use(bodyParser())

//  配置静态资源
const static = require('koa-static')
// app.use(static('static'))
app.use(static(__dirname + '/static'))

//模板引擎 art-template
const render = require('koa-art-template')
render(app, {
  root: path.join(__dirname, 'views'),
  extname: '.html',
  debug: process.env.NODE_ENV !== 'production',
})

//  应用级中间件中间件
app.use(async (ctx, next) => {
  console.log(new Date())
  await next()
})

// mongoDB
const DB = require('./module/db')

// 路由
router.get('/', async (ctx) => {
  let res = await DB.find('user')
  await ctx.render('index', {
    list: res,
  })
})

router.get('/add', async (ctx) => {
  await ctx.render('add')
})

router.post('/doAdd', async (ctx) => {
  let data = ctx.request.body
  let res = await DB.insert('user', data)
  if (res) {
    ctx.redirect('/')
  }
})

router.get('/edit', async (ctx) => {
  // let res = await DB.find('user')

  let id = ctx.query.id
  let data = await DB.find('user', {
    _id: DB.getObjectID(id),
  })

  await ctx.render('edit', {
    list: data[0],
  })
})
router.get('/doEdit', async (ctx) => {
  // let id = ctx.request.body.id

  const { id, name, name } = ctx.request.body

  let data = await DB.update('user', { _id: DB.getObjectID(id) }, { name, age })
})

router.get('/delect', async (ctx) => {
  let id = ctx.query.id

  let data = await DB.remove('user', { _id: DB.getObjectID(id) })
})

router.post('/doLogin', async (ctx) => {
  ctx.body = ctx.request.body
})
router.get('/news', async (ctx) => {
  //  获取get 传参  ctx.query
  ctx.body = '新闻路由'
})

router.get('/newscount/:uid/:cid', async (ctx) => {
  //  获取get 传参  ctx.query
  ctx.body = '动态路由'
})

app
  .use(router.routes()) // 启动路由
  .use(router.allowedMethods())
app.listen(3000)
